<?php

namespace App\Http\Controllers\Api;

use App\Donation;
use App\Events\CoursePaid;
use App\Events\OrderPaid;
use App\Order;
use App\SubjectPower;
use App\TalentsSystemOrder;
use App\Upgrade;
use App\User;
use App\UserCourse;
use App\UserPersonnel;
use Carbon\Carbon;
use EasyWeChat\Factory;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class NotifyController extends Controller
{
    protected $type;
    protected $id;

    /**
     * 支付成功异步通知业务处理
     * @param $type
     * @param $id
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function notify($type, $id)
    {
        $this->type = $type;
        $this->id = $id;

        if ($type == 'wxpay') {
            return $this->_wxpay();
        }
        return null;
    }

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    protected function _wxpay()
    {
        $app = Factory::payment(config('wechat.payment.default'));
        $response = $app->handlePaidNotify(function ($message, $fail) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = Order::where('order_sn', $message['out_trade_no'])->first();

            if (!$order || $order->pay_status) { // 如果订单不存在 或者paid_at 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->paid_at = Carbon::now(); // 更新支付时间为当前时间
                    $order->pay_status = 1;
                    $order->pay_name = '微信支付';
                    $order->pay_code = 'JSAPI';
                    // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->pay_status = 0;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            $order->save(); // 保存订单
            if ($order->pay_status === 1) { // 订单日志
                event(new OrderPaid($order));
            }
            return true; // 返回处理完成
        });
        return $response;
    }

    /**
     * @param $type
     * @param $id
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     * 全款成功异步处理
     */
    public function donation($type, $id)
    {
        $app = Factory::payment(config('wechat.payment.default'));
        $response = $app->handlePaidNotify(function ($message, $fail) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = Donation::where('order_sn', $message['out_trade_no'])->first();

            if (!$order || $order->status) { // 如果订单不存在 或者paid_at 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->status = 1;
                    // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->status = 0;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            $order->save(); // 保存订单
            return true; // 返回处理完成
        });
        return $response;
    }

    /**
     * @param $type
     * @param $id
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     * 购买课程成功异步处理
     */
    public function course($type, $id)
    {
        $app = Factory::payment(config('wechat.payment.default'));
        $response = $app->handlePaidNotify(function ($message, $fail) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = UserCourse::where('order_sn', $message['out_trade_no'])->first();

            if (!$order || $order->pay_status) {
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->pay_status = 1;
                    $order->paid_at = Carbon::now();
                    // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->pay_status = 0;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            $order->save(); // 保存订单
            if ($order->pay_status === 1) { // 订单日志
                event(new CoursePaid($order));
            }
            return true; // 返回处理完成
        });
        return $response;
    }

    /**
     * @param $type
     * @param $id
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     * 会员升级成功异步处理
     */
    public function upgrade($type, $id)
    {
        $app = Factory::payment(config('wechat.payment.default'));
        $response = $app->handlePaidNotify(function ($message, $fail) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = Upgrade::where('order_sn', $message['out_trade_no'])->first();

            if (!$order || $order->status) { // 如果订单不存在 或者paid_at 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->status = 1;
                    User::where('id', $order->user_id)->update(['level_id' => $order->level_id]);
                    // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->status = 0;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            $order->save(); // 保存订单
            return true; // 返回处理完成
        });
        return $response;
    }

    /**
     * @param $type
     * @param $id
     * @return null|\Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function vipNotify($type, $id)
    {
        $this->type = $type;
        $this->id = $id;

        if ($type == 'wxpay') {
            return $this->_openVipwxpay();
        }
        return null;
    }

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    protected function _openVipwxpay()
    {
        $app = Factory::payment(config('wechat.payment.default'));
        $response = $app->handlePaidNotify(function ($message, $fail) {
            $order = TalentsSystemOrder::where('order_number', $message['out_trade_no'])->first();

            if (!$order || $order->pay_status) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    #修改订单状态
                    $order->confirmed_at = Carbon::now();
                    $order->pay_status = 1;
                    $order->pay_type = 'WXPAY';
                    #修改用户vip时间
                    $user = UserPersonnel::where('user_id', $order->user_id)->first();
                    if ($user->vip_over_time >= time()) {
                        $time = $user->vip_over_time + $order->month * 30 * 24 * 60 * 60;
                    } else {
                        $time = strtotime(date('Y-m-d')) + $order->month * 30 * 24 * 60 * 60;
                    }
                    $user->vip_over_time = $time;
                    $user->save();
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->confirmed_at = Carbon::now();
                    $order->pay_status = 0;
                    $order->pay_type = 'WXPAY';
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            $order->save();
            return true;
        });
        return $response;
    }

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function subject()
    {
        $app = Factory::payment(config('wechat.payment.default'));
        $response = $app->handlePaidNotify(function ($message, $fail) {
            $order = TalentsSystemOrder::where('order_number', $message['out_trade_no'])->first();
            if (!$order || $order->pay_status) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->pay_status = 1;
                    $order->pay_type = 'WXPAY';
                    $order->confirmed_at = date('Y-m-d H:i:s');
                    #给用户做题权限
                    SubjectPower::create([
                        'user_id' => $order->user_id,
                        'subject_sort_id' => $order->subject_sort_id,
                    ]);
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->pay_status = 0;
                    $order->pay_type = 'WXPAY';
                    $order->confirmed_at = date('Y-m-d H:i:s');
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            $order->save();
            return true;
        });
        return $response;
    }

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function team()
    {
        $app = Factory::payment(config('wechat.payment.default'));
        $response = $app->handlePaidNotify(function ($message, $fail) {
            $order = TalentsSystemOrder::where('order_number', $message['out_trade_no'])->first();
            if (!$order || $order->pay_status) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->pay_status = 1;
                    $order->pay_type = 'WXPAY';
                    $order->confirmed_at = date('Y-m-d H:i:s');
                    #给用户做题权限
                    $teamArr = explode(',', $order->team_user_id);
                    foreach ($teamArr as $v) {
                        SubjectPower::create([
                            'user_id' => $v,
                            'subject_sort_id' => 2,//默认做完整评估这套题目
                        ]);
                    }
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->pay_status = 0;
                    $order->pay_type = 'WXPAY';
                    $order->confirmed_at = date('Y-m-d H:i:s');
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            $order->save();
            return true;
        });
        return $response;
    }
}
